package com.tlzh.controller;


import com.tlzh.pojo.dto.ChatRequest;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;

@RestController
@RequestMapping("/sse")
@CrossOrigin
public class SseEmitterController {

    private final RestTemplate restTemplate = new RestTemplate();
    // 重写请求 URL 和方法名称
    // 普通用户
    @PostMapping(value = "/ai/ollamaChatStream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter chatModel(@RequestBody ChatRequest request) {
        SseEmitter emitter = new SseEmitter();

        new Thread(() -> {
            try {
                // 实际的 API 地址，你需要根据实际情况修改
                String apiUrl = "http://192.168.0.188:11434/api/chat";

                // 发送 POST 请求
                ResponseEntity<String> responseEntity = restTemplate.postForEntity(apiUrl, request, String.class);
                String response = responseEntity.getBody();

                // 模拟将响应数据拆分为多个部分进行流式发送
                if (response != null) {
                    String[] parts = response.split("(?<=\\})(?=\\{)");
                    for (String part : parts) {
                        SseEmitter.SseEventBuilder event = SseEmitter.event()
                                .data(part)
                                .id(String.valueOf(System.currentTimeMillis()))
                                .reconnectTime(5000);
                        emitter.send(event);
                        Thread.sleep(100); // 模拟延迟
                    }
                }
                emitter.complete();
            } catch (IOException | InterruptedException e) {
                emitter.completeWithError(e);
            }
        }).start();

        return emitter;
    }




}
